﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace WpfRedis.Common
{
    public class PasswordHelper
    {
        public static string GetPassword(DependencyObject obj)
        {
            return (string)obj.GetValue(PasswordProperty);
        }

        public static void SetPassword(DependencyObject obj, string value)
        {
            obj.SetValue(PasswordProperty, value);
        }
        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PasswordHelper), new PropertyMetadata("", new PropertyChangedCallback(OnPasswardChanged)));

        private static void OnPasswardChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is PasswordBox box)
            {
                if (e.NewValue is null) return;
                if (!_isupdate) box.Password = e.NewValue.ToString();
            }
        }

        public static bool GetEnableBinding(DependencyObject obj)
        {
            return (bool)obj.GetValue(EnableBindingProperty);
        }

        public static void SetEnableBinding(DependencyObject obj, bool value)
        {
            obj.SetValue(EnableBindingProperty, value);
        }

        public static readonly DependencyProperty EnableBindingProperty =
            DependencyProperty.RegisterAttached("EnableBinding", typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false, new PropertyChangedCallback(OnEnableBindingChanged)));

        private static void OnEnableBindingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is PasswordBox box)
            {
                if ((bool)e.NewValue)
                {
                    box.PasswordChanged += Box_PasswordChanged;
                }
                else
                {
                    box.PasswordChanged -= Box_PasswordChanged;
                }
            }
        }
        static bool _isupdate = false;
        private static void Box_PasswordChanged(object sender, RoutedEventArgs e)
        {
            var pass = sender as PasswordBox;
            _isupdate = true;
            SetPassword(pass, pass?.Password);
            _isupdate = false;
        }
    }
}
